<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系统管理中心 - 新商城</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100">
    <header class="bg-white shadow-md">
        <div class="container mx-auto px-4 py-4 flex justify-between items-center">
            <div class="text-2xl font-bold text-blue-600">新商城 - 系统管理</div>
            <div class="flex items-center space-x-6">
                <div class="relative">
                    <button id="systemUserMenuBtn" class="flex items-center space-x-2 focus:outline-none">
                        <i class="fa fa-user-circle text-xl text-gray-600"></i>
                        <span id="usernameDisplay" class="text-gray-700"></span>
                        <i class="fa fa-chevron-down text-xs text-gray-500"></i>
                    </button>
                    <div id="systemUserMenu" class="absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 hidden z-10">
                        <a href="#" id="logoutBtn" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
                            <i class="fa fa-sign-out mr-2"></i>退出登录
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </header>

    <main class="container mx-auto px-4 py-8">
        <div class="flex flex-col md:flex-row gap-6">
            <!-- 侧边导航 -->
            <div class="w-full md:w-64 bg-white rounded-lg shadow-md p-4">
                <nav class="space-y-1">
                    <a href="#dashboard" class="nav-link active block px-4 py-3 rounded-md bg-purple-50 text-purple-600 font-medium">
                        <i class="fa fa-home mr-3"></i>系统首页
                    </a>
                    <a href="#user-management" class="nav-link block px-4 py-3 rounded-md text-gray-700 hover:bg-gray-100 font-medium">
                        <i class="fa fa-users mr-3"></i>用户管理
                    </a>
                    <a href="#goods-management" class="nav-link block px-4 py-3 rounded-md text-gray-700 hover:bg-gray-100 font-medium">
                        <i class="fa fa-shopping-bag mr-3"></i>商品管理
                    </a>
                    <a href="#order-management" class="nav-link block px-4 py-3 rounded-md text-gray-700 hover:bg-gray-100 font-medium">
                        <i class="fa fa-list-alt mr-3"></i>订单管理
                    </a>
                    <a href="#system-settings" class="nav-link block px-4 py-3 rounded-md text-gray-700 hover:bg-gray-100 font-medium">
                        <i class="fa fa-cog mr-3"></i>系统设置
                    </a>
                </nav>
            </div>

            <!-- 主内容区 -->
            <div class="flex-1 space-y-6">
                <!-- 欢迎信息 -->
                <div id="dashboard-section" class="bg-white rounded-lg shadow-md p-6">
                    <h2 class="text-2xl font-bold mb-2">欢迎回来，系统管理员 <span id="welcomeUsername"></span>！</h2>
                    <p class="text-gray-600">在这里可以管理所有用户和系统配置</p>
                </div>

                <!-- 用户列表 -->
                <div id="user-management-section" class="bg-white rounded-lg shadow-md p-6">
                    <div class="flex justify-between items-center mb-6">
                        <h2 class="text-xl font-bold">用户管理</h2>
                    </div>
                    
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">用户名</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">昵称</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">手机号</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">邮箱</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                                </tr>
                            </thead>
                            <tbody id="userList" class="bg-white divide-y divide-gray-200">
                                <!-- 用户数据将通过JavaScript动态加载 -->
                            </tbody>
                        </table>
                        <!-- 补充内容 -->
                        <table class="min-w-full bg-white">
                            <thead>
                                <tr>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">用户名</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">店铺名称</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">联系人</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">电话</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">地址</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">店铺描述</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                                </tr>
                            </thead>
                            <tbody id="merchantList" class="bg-white divide-y divide-gray-200">
                                <!-- 商家数据将通过JavaScript动态加载 -->
                            </tbody>
                        </table>
                        <!--补充内容  -->
                    </div>
                </div>
                <!--商品管理  -->
                <div id="goods-management-section" class="hidden">
                    <div class="bg-white rounded-lg shadow-md p-6">
                        <div class="flex justify-between items-center mb-6">
                            <h2 class="text-xl font-bold">商品管理</h2>
                        </div>
                        
                        <div class="overflow-x-auto">
                            <table class="min-w-full divide-y divide-gray-200">
                                <thead class="bg-gray-50">
                                    <tr>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">商品名称</th>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">所属商家</th>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">价格</th>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                                    </tr>
                                </thead>
                                <tbody id="goodsList" class="bg-white divide-y divide-gray-200">
                                    <!-- 商品数据将通过JavaScript动态加载 -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- 在主内容区添加系统设置部分 -->
                <div id="system-settings-section" class="hidden">
                    <div class="bg-white rounded-lg shadow-md p-6">
                        <h2 class="text-xl font-bold mb-6">系统设置</h2>
                        
                        <div class="space-y-6">
                            <div>
                                <h3 class="text-lg font-semibold mb-4">管理员信息设置</h3>
                                <form id="adminProfileForm" class="space-y-4">
                                    <div>
                                        <label for="adminUsername" class="block text-gray-700 mb-2">用户名</label>
                                        <input type="text" id="adminUsername" class="w-full px-3 py-2 border border-gray-300 rounded-md">
                                    </div>
                    
                                    <div>
                                        <label for="adminPassword" class="block text-gray-700 mb-2">密码</label>
                                        <input type="password" id="adminPassword" class="w-full px-3 py-2 border border-gray-300 rounded-md" placeholder="不修改请留空">
                                    </div>
                    
                                    <button type="submit" class="px-6 py-2 bg-purple-600 text-white rounded-md hover:bg-purple-700 transition">
                                        保存设置
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 订单管理区域 -->
                <div id="order-management-section" class="hidden"> <!-- 关键：添加id和hidden类 -->
                    <div class="mt-8">
                        <div class="flex justify-between items-center mb-4">
                            <h2 class="text-2xl font-bold">订单管理</h2>
                        </div>
    
                        <!-- 筛选区域 -->
                        <div class="bg-white p-4 rounded-lg shadow mb-6">
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">发送人筛选</label>
                                    <input type="text" id="senderFilter" placeholder="输入发送人名称"   
                            class="w-full px-3 py-2 border border-gray-300 rounded-md">
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">收货人筛选</label>
                                    <input type="text" id="receiverFilter" placeholder="输入收货人名称" 
                                       class="w-full px-3 py-2 border border-gray-300 rounded-md">
                                </div>
                            </div>
                        <div class="mt-3 flex justify-end">
                            <button onclick="filterOrders()" class="bg-blue-500 text-white px-4 py-2 rounded-md hover:bg-blue-600">
                                筛选订单
                            </button>
                            <button onclick="loadAllOrders()" class="ml-2 bg-gray-200 text-gray-700 px-4 py-2 rounded-md hover:bg-gray-300">
                                显示全部
                            </button>
                        </div>
                    </div>
                </div>
    
                <!-- 订单列表 -->
                <div class="mt-8">
                    <div class="bg-white rounded-lg shadow overflow-hidden">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">订单ID</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">商品名称</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">价格</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">发送人</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">收货人</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                                </tr>
                            </thead>
                            <tbody id="orderList" class="bg-white divide-y divide-gray-200">
                                <!-- 订单数据将通过JS动态加载 -->
                            </tbody>
                        </table>
                    </div>
                </div>
                </div>
            </div>
        </div>
</main>

    <footer class="bg-gray-800 text-white py-8 mt-16">
        <div class="container mx-auto px-4 text-center">
            <p>© 2025 新商城 版权所有</p>
        </div>
    </footer>

    <script>
        // 当前登录系统用户信息
        let currentSystemUser = null;

        // 页面加载完成后初始化
        window.addEventListener('DOMContentLoaded', async () => {
            // 检查登录状态
            const systemUserStr = localStorage.getItem('systemUser');
            if (!systemUserStr) {
                window.location.href = 'system-login.html';
                return;
            }
            
            currentSystemUser = JSON.parse(systemUserStr);
            
            // 显示用户名
            document.getElementById('usernameDisplay').textContent = currentSystemUser.username;
            document.getElementById('welcomeUsername').textContent = currentSystemUser.username;

             document.getElementById('userEditForm').addEventListener('submit', handleUserEditSubmit);
            
             // 初始化导航
            setupNavigation();
    
            // 初始化管理员信息表单
            initAdminProfileForm();

            // 加载用户列表
            await loadUserList();

            loadMerchantList(); // 加载商家列表

            // 绑定事件
            bindEvents();
        });

        // 加载用户列表
        async function loadUserList() {
            try {
                const response = await fetch('http://localhost:8080/api/system/users');
                const result = await response.json();
                
                if (result.success) {
                    const userListElement = document.getElementById('userList');
                    userListElement.innerHTML = '';
                    
                    result.data.forEach(user => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${user.id}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${user.username}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${user.nickname || '-'}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${user.phone || '-'}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${user.email || '-'}</td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${user.status === 1 ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}">
                                    ${user.status === 1 ? '正常' : '禁用'}
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                <button onclick="editUser(${user.id})" class="text-purple-600 hover:text-purple-900 mr-3">编辑</button>
                                <button onclick="disableUser(${user.id}, ${user.status === 1})" class="text-red-600 hover:text-red-900">
                                    ${user.status === 1 ? '禁用' : '启用'}
                                </button>
                            </td>
                        `;
                        userListElement.appendChild(row);
                    });
                } else {
                    alert('获取用户列表失败: ' + (result.message || '未知错误'));
                }
            } catch (error) {
                console.error('加载用户列表失败:', error);
                alert('加载用户列表失败，请稍后重试');
            }
        }

        // 添加用户编辑功能
    async function editUser(userId) {
        try {
            const response = await fetch(`http://localhost:8080/api/system/users/${userId}`);
            const result = await response.json();
    
            if (result.success && result.data) {  // 确保数据存在
                const user = result.data;
                // 检查DOM元素是否存在
                const editUserId = document.getElementById('editUserId');
                const editUsername = document.getElementById('editUsername');
                const editNickname = document.getElementById('editNickname');
                const editPhone = document.getElementById('editPhone');
                const editEmail = document.getElementById('editEmail');
            
                // 确保所有元素都存在
                if (!editUserId || !editUsername || !editNickname || !editPhone || !editEmail) {
                    throw new Error('编辑表单元素缺失');
                }
            
                // 填充编辑表单
                editUserId.value = user.id;
                editUsername.value = user.username;
                editNickname.value = user.nickname || '';
                editPhone.value = user.phone || '';
                editEmail.value = user.email || '';
            
                // 显示编辑模态框
                document.getElementById('userEditModal').classList.remove('hidden');
            } else {
                alert('获取用户信息失败: ' + (result.message || '未知错误'));
            }
        } catch (error) {
            console.error('获取用户信息失败:', error);
            alert('获取用户信息失败');
        }
    }

// 添加用户禁用功能
    async function disableUser(userId, disable) {
        if (confirm(disable ? '确定要禁用该用户吗？' : '确定要启用该用户吗？')) {
        try {
            // 计算目标状态：禁用操作对应状态0，启用对应状态1
            const targetStatus = disable ? 0 : 1;
            // 使用URL参数传递id和status
            const response = await fetch(`http://localhost:8080/api/system/users/status?id=${userId}&status=${targetStatus}`, {
                method: 'PUT'
});
            
            const result = await response.json();
            if (result.success) {
                alert('操作成功');
                // 重新加载用户列表
                loadUserList();
            } else {
                alert('操作失败: ' + (result.message || '未知错误'));
            }
        } catch (error) {
            console.error('修改用户状态失败:', error);
            alert('修改用户状态失败');
        }
    }
}

async function loadGoodsList() {
    try {
        const response = await fetch('http://localhost:8080/api/system/goods');
        const result = await response.json();
        
        if (result.success) {
            const goodsListElement = document.getElementById('goodsList');
            goodsListElement.innerHTML = '';
            
            result.data.forEach(good => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${good.goodid}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${good.goodname}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${good.merchant_shopname || '-'}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">¥${good.price}</td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">
                            上架
                        </span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        <button onclick="removeGood(${good.goodid})" class="text-red-600 hover:text-red-900">下架</button>
                    </td>
                `;
                goodsListElement.appendChild(row);
            });
        } else {
            alert('获取商品列表失败: ' + (result.message || '未知错误'));
        }
    } catch (error) {
        console.error('加载商品列表失败:', error);
        alert('加载商品列表失败，请稍后重试');
    }
}

// 下架商品
async function removeGood(goodId) {
    if (confirm('确定要下架该商品吗？')) {
        try {
            const response = await fetch(`http://localhost:8080/api/system/goods?goodId=${goodId}`, {
                method: 'DELETE'
            });
            
            const result = await response.json();
            if (result.success) {
                alert('商品已成功下架');
                loadGoodsList();  // 重新加载商品列表
            } else {
                alert(result.message || '下架失败');
            }
        } catch (error) {
            console.error('下架商品失败:', error);
            alert('下架商品失败');
        }
    }
}


// 处理用户编辑表单提交
async function handleUserEditSubmit(e) {
    e.preventDefault();
    const userId = document.getElementById('editUserId').value;
    const userData = {
        id: userId,
        username: document.getElementById('editUsername').value,
        nickname: document.getElementById('editNickname').value,
        phone: document.getElementById('editPhone').value,
        email: document.getElementById('editEmail').value
    };

    try {
        const response = await fetch('http://localhost:8080/api/system/users/update', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(userData)
        });

        const result = await response.json();
        if (result.success) {
            alert('用户信息更新成功');
            document.getElementById('userEditModal').classList.add('hidden');
            loadUserList(); // 刷新用户列表
        } else {
            alert('更新失败: ' + (result.message || '未知错误'));
        }
    } catch (error) {
        console.error('更新用户信息失败:', error);
        alert('更新用户信息失败，请稍后重试');
    }
}



        // 绑定事件
        function bindEvents() {
            // 系统用户菜单切换
            document.getElementById('systemUserMenuBtn').addEventListener('click', () => {
                document.getElementById('systemUserMenu').classList.toggle('hidden');
            });
            
            // 新增：编辑用户表单提交事件
            document.getElementById('userEditForm').addEventListener('submit', async (e) => {
                e.preventDefault();
                
                const userId = document.getElementById('editUserId').value;
                const userData = {
                    id: userId,
                    username: document.getElementById('editUsername').value,
                    nickname: document.getElementById('editNickname').value,
                    phone: document.getElementById('editPhone').value,
                    email: document.getElementById('editEmail').value,
                    // 可根据需要添加其他字段（如状态等）
                };
                
                try {
                    // 注意：API地址建议与后端保持一致，参考用户更新的地址风格，可能需要改为 /api/system/users/update
                    const response = await fetch(`http://localhost:8080/api/system/users/update`, {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(userData)
                    });
            
                const result = await response.json();
                if (result.success) {
                    alert('用户信息更新成功');
                    document.getElementById('userEditModal').classList.add('hidden');
                    loadUserList(); // 重新加载用户列表，刷新显示
                } else {
                    alert('更新失败: ' + (result.message || '未知错误'));
                }
            } catch (error) {
                console.error('更新用户信息失败:', error);
                alert('更新用户信息失败');
            }
        });
            
            // 点击其他区域关闭用户菜单
            document.addEventListener('click', (e) => {
                const userMenuBtn = document.getElementById('systemUserMenuBtn');
                const userMenu = document.getElementById('systemUserMenu');
                
                if (!userMenuBtn.contains(e.target) && !userMenu.contains(e.target)) {
                    userMenu.classList.add('hidden');
                }
            });
            
            // 退出登录
            document.getElementById('logoutBtn').addEventListener('click', () => {
                localStorage.removeItem('systemUser');
                window.location.href = 'index.html';
            });
        }
        
        function setupNavigation() {
            const navLinks = document.querySelectorAll('.nav-link');
            const contentSections = {
                'dashboard': document.getElementById('dashboard-section'),
                'user-management': document.getElementById('user-management-section'),
                'goods-management': document.getElementById('goods-management-section'),
                'order-management': document.getElementById('order-management-section'),
                'system-settings': document.getElementById('system-settings-section')
            };

            navLinks.forEach(link => {
                link.addEventListener('click', function(e) {
                    e.preventDefault();
                    const targetId = this.getAttribute('href').substring(1);
    
                    // 更新导航样式
                    navLinks.forEach(l => {
                        l.classList.remove('active', 'bg-purple-50', 'text-purple-600');
                        l.classList.add('text-gray-700', 'hover:bg-gray-100');
                    }); 
                    this.classList.add('active', 'bg-purple-50', 'text-purple-600');
                    this.classList.remove('text-gray-700', 'hover:bg-gray-100');

                    // 显示对应内容区域
                    Object.entries(contentSections).forEach(([id, section]) => {
                        if (!section) return;
                        
                        if (id === targetId) {
                            section.classList.remove('hidden');
                            // 加载对应数据
                            if (id === 'user-management') loadUserList();
                            if (id === 'goods-management') loadGoodsList();
                            if (id === 'order-management') loadAllOrders(); // 新增订单数据加载
                        } else {
                            section.classList.add('hidden');
                        }
                    });
                });
            });
}

// 加载所有订单
async function loadAllOrders() {
    try {
        const response = await fetch('http://localhost:8080/api/system/orders', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        });
        
        const result = await response.json();
        
        if (result.success && result.data) {
            renderOrderList(result.data);
        } else {
            alert('加载订单失败: ' + (result.message || '未知错误'));
        }
    } catch (error) {
        console.error('加载订单失败:', error);
        alert('加载订单失败，请稍后重试');
    }
}

// 筛选订单
function filterOrders() {
    const sender = document.getElementById('senderFilter').value.toLowerCase();
    const receiver = document.getElementById('receiverFilter').value.toLowerCase();
    
    // 获取所有订单行
    const rows = document.querySelectorAll('#orderList tr');
    
    rows.forEach(row => {
        const senderText = row.getAttribute('data-sender').toLowerCase();
        const receiverText = row.getAttribute('data-receiver').toLowerCase();
        
        // 检查是否匹配筛选条件
        const senderMatch = sender === '' || senderText.includes(sender);
        const receiverMatch = receiver === '' || receiverText.includes(receiver);
        
        row.style.display = senderMatch && receiverMatch ? '' : 'none';
    });
}

// 渲染订单列表
function renderOrderList(orders) {
    const orderListElement = document.getElementById('orderList');
    orderListElement.innerHTML = '';
    
    if (orders.length === 0) {
        orderListElement.innerHTML = `
            <tr>
                <td colspan="7" class="px-6 py-4 text-center text-gray-500">
                    暂无订单数据
                </td>
            </tr>
        `;
        return;
    }
    
    orders.forEach(order => {
        const row = document.createElement('tr');
        row.setAttribute('data-sender', order.sender_username || '');
        row.setAttribute('data-receiver', order.receiver_username || '');
        
        row.innerHTML = `
            <td class="px-6 py-4 whitespace-nowrap">${order.id}</td>
            <td class="px-6 py-4 whitespace-nowrap">${order.goodname}</td>
            <td class="px-6 py-4 whitespace-nowrap">¥${order.price}</td>
            <td class="px-6 py-4 whitespace-nowrap">${order.senderUsername || '未知商家'}</td>
            <td class="px-6 py-4 whitespace-nowrap">${order.receiverUsername || '未知用户'}</td>
            <td class="px-6 py-4 whitespace-nowrap">
                ${order.createtime ? new Date(order.createtime).toLocaleString() : ''}
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
                <button onclick="recallOrder(${order.id})" 
                        class="bg-red-500 text-white px-3 py-1 rounded-md hover:bg-red-600 text-sm">
                    撤回订单
                </button>
            </td>
        `;
        
        orderListElement.appendChild(row);
    });
}

// 撤回订单
async function recallOrder(orderId) {
    if (confirm(`确定要撤回订单 #${orderId} 吗？此操作将删除订单并将商品归还商家。`)) {
        try {
            const response = await fetch(`http://localhost:8080/api/system/orders/recall?orderId=${orderId}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            
            const result = await response.json();
            
            if (result.success) {
                alert('订单撤回成功');
                loadAllOrders(); // 重新加载订单列表
            } else {
                alert('撤回失败: ' + (result.message || '未知错误'));
            }
        } catch (error) {
            console.error('撤回订单失败:', error);
            alert('撤回订单失败，请稍后重试');
        }
    }
}

// 初始化管理员信息表单
function initAdminProfileForm() {
    if (currentSystemUser) {
        document.getElementById('adminUsername').value = currentSystemUser.username || '';
    }
    
    // 表单提交事件
    document.getElementById('adminProfileForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const username = document.getElementById('adminUsername').value;
        const password = document.getElementById('adminPassword').value;
        
        try {
            const response = await fetch('http://localhost:8080/api/system/profile', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    id: currentSystemUser.id,
                    username,
                    password: password || undefined  // 密码为空则不修改
                })
            });
            
            const result = await response.json();
            if (result.success) {
                alert('设置保存成功');
                // 更新本地存储的用户信息
                currentSystemUser.username = username;
                localStorage.setItem('systemUser', JSON.stringify(currentSystemUser));
                document.getElementById('usernameDisplay').textContent = username;
                document.getElementById('welcomeUsername').textContent = username;
            } else {
                alert(result.message || '保存失败');
            }
        } catch (error) {
            console.error('保存系统设置失败:', error);
            alert('保存设置失败');
        }
    });
}   
function closeEditModal() {
  document.getElementById('userEditModal').classList.add('hidden');
}

async function loadMerchantList() {
  try {
    const response = await fetch('http://localhost:8080/api/system/merchants');
    const result = await response.json();
    
    if (result.success) {
      const merchantListElement = document.getElementById('merchantList');
      merchantListElement.innerHTML = '';
      
      result.data.forEach(merchant => {
        const row = document.createElement('tr');
        // 状态显示文本（1=正常，0=封禁）
        const statusText = merchant.status === 1 ? '正常' : '已封禁';
        const statusClass = merchant.status === 1 ? 'text-green-600' : 'text-red-600';
        // 按钮文本和操作类型
        const buttonText = merchant.status === 1 ? '封禁' : '启用';
        const isDisable = merchant.status === 1;
        
        row.innerHTML = `
            <td class="px-6 py-4 whitespace-nowrap">${merchant.id}</td>
            <td class="px-6 py-4 whitespace-nowrap">${merchant.username || '未知'}</td>
            <td class="px-6 py-4 whitespace-nowrap">${merchant.shopname || '未设置'}</td>
            <td class="px-6 py-4 whitespace-nowrap">${merchant.contact_person || '暂无'}</td>
            <td class="px-6 py-4 whitespace-nowrap">${merchant.phone || '未填写'}</td>
            <td class="px-6 py-4 whitespace-nowrap">${merchant.address || '未填写'}</td>
            <td class="px-6 py-4 whitespace-nowrap">${merchant.shop_desc || '暂无'}</td>
            <td class="px-6 py-4 whitespace-nowrap">
                <span class="${statusClass}">${statusText}</span>
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
                <button onclick="editMerchant(${merchant.id})" 
                    class="px-3 py-1 bg-blue-500 text-white rounded mr-2">
                    编辑
                </button>
                <button onclick="updateMerchantStatus(${merchant.id}, ${isDisable})" 
                    class="px-3 py-1 rounded ${isDisable ? 'bg-red-500 text-white' : 'bg-green-500 text-white'}">
                    ${buttonText}
                </button>
            </td>
        `;
        merchantListElement.appendChild(row);
      });
    } else {
      alert('获取商家列表失败: ' + (result.message || '未知错误'));
    }
  } catch (error) {
    console.error('加载商家列表失败:', error);
    alert('加载商家列表失败');
  }
}

// 修改商家状态（封禁/启用）
async function updateMerchantStatus(merchantId, disable) {
  if (confirm(disable ? '确定要封禁该商家吗？' : '确定要启用该商家吗？')) {
    try {
      // 目标状态：封禁=0，启用=1
      const targetStatus = disable ? 0 : 1;
      const response = await fetch(`http://localhost:8080/api/system/merchants/status?id=${merchantId}&status=${targetStatus}`, {
        method: 'PUT'
      });
      
      const result = await response.json();
      if (result.success) {
        alert('操作成功');
        loadMerchantList(); // 重新加载列表
      } else {
        alert('操作失败: ' + (result.message || '未知错误'));
      }
    } catch (error) {
      console.error('修改商家状态失败:', error);
      alert('修改商家状态失败');
    }
  }
}

// 打开商家编辑模态框并加载数据
async function editMerchant(merchantId) {
  try {
    const response = await fetch(`http://localhost:8080/api/merchant/${merchantId}`);
    const result = await response.json();
    
    if (result.success) {
      const merchant = result.data;
      // 填充编辑表单
      document.getElementById('editMerchantId').value = merchant.id;
      document.getElementById('editMerchantUsername').value = merchant.username;
      document.getElementById('editMerchantShopname').value = merchant.shopname || '';
      document.getElementById('editMerchantContact').value = merchant.contact_person || '';
      document.getElementById('editMerchantPhone').value = merchant.phone || '';
      document.getElementById('editMerchantAddress').value = merchant.address || '';
      document.getElementById('editMerchantDesc').value = merchant.shop_desc || '';
      
      // 显示编辑模态框
      document.getElementById('merchantEditModal').classList.remove('hidden');
    } else {
      alert('获取商家信息失败: ' + (result.message || '未知错误'));
    }
  } catch (error) {
    console.error('获取商家信息失败:', error);
    alert('获取商家信息失败');
  }
}

// 关闭商家编辑模态框
function closeMerchantEditModal() {
  document.getElementById('merchantEditModal').classList.add('hidden');
}

// 提交商家编辑表单
document.getElementById('merchantEditForm').addEventListener('submit', async function(e) {
  e.preventDefault();
  
  const merchantId = document.getElementById('editMerchantId').value;
  const merchantData = {
    id: merchantId,
    username: document.getElementById('editMerchantUsername').value,
    shopname: document.getElementById('editMerchantShopname').value,
    contact_person: document.getElementById('editMerchantContact').value,
    phone: document.getElementById('editMerchantPhone').value,
    address: document.getElementById('editMerchantAddress').value,
    shop_desc: document.getElementById('editMerchantDesc').value
  };
  
  try {
    const response = await fetch('http://localhost:8080/api/merchant/update', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(merchantData)
    });
    
    const result = await response.json();
    if (result.success) {
      alert('商家信息更新成功');
      document.getElementById('merchantEditModal').classList.add('hidden');
      loadMerchantList(); // 刷新商家列表
    } else {
      alert('更新失败: ' + (result.message || '未知错误'));
    }
  } catch (error) {
    console.error('更新商家信息失败:', error);
    alert('更新商家信息失败，请稍后重试');
  }
});

    </script>

    <!-- 用户编辑模态框 -->
<div id="userEditModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
  <div class="bg-white rounded-lg p-6 w-full max-w-md">
    <h3 class="text-xl font-bold mb-4">编辑用户</h3>
    <form id="userEditForm">
      <!-- 隐藏域存储用户ID -->
      <input type="hidden" id="editUserId">
      
      <div class="mb-4">
        <label class="block mb-2">用户名</label>
        <input type="text" id="editUsername" class="w-full p-2 border rounded" readonly>
      </div>
      
      <div class="mb-4">
        <label class="block mb-2">昵称</label>
        <input type="text" id="editNickname" class="w-full p-2 border rounded">
      </div>
      
      <div class="mb-4">
        <label class="block mb-2">手机号</label>
        <input type="text" id="editPhone" class="w-full p-2 border rounded">
      </div>
      
      <div class="mb-4">
        <label class="block mb-2">邮箱</label>
        <input type="email" id="editEmail" class="w-full p-2 border rounded">
      </div>
      
      <div class="flex justify-end gap-2">
        <button type="button" onclick="closeEditModal()" class="px-4 py-2 border rounded">取消</button>
        <button type="submit" class="px-4 py-2 bg-blue-500 text-white rounded">保存</button>
      </div>
    </form>
  </div>
</div>
<!-- 商家编辑模态框 -->
<div id="merchantEditModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
  <div class="bg-white rounded-lg p-6 w-full max-w-md">
    <h3 class="text-xl font-bold mb-4">编辑商家</h3>
    <form id="merchantEditForm">
      <!-- 隐藏域存储商家ID -->
      <input type="hidden" id="editMerchantId">
      
      <div class="mb-4">
        <label class="block mb-2">用户名</label>
        <input type="text" id="editMerchantUsername" class="w-full p-2 border rounded" readonly>
      </div>
      
      <div class="mb-4">
        <label class="block mb-2">店铺名称</label>
        <input type="text" id="editMerchantShopname" class="w-full p-2 border rounded">
      </div>
      
      <div class="mb-4">
        <label class="block mb-2">联系人</label>
        <input type="text" id="editMerchantContact" class="w-full p-2 border rounded">
      </div>
      
      <div class="mb-4">
        <label class="block mb-2">手机号</label>
        <input type="text" id="editMerchantPhone" class="w-full p-2 border rounded">
      </div>
      
      <div class="mb-4">
        <label class="block mb-2">店铺地址</label>
        <input type="text" id="editMerchantAddress" class="w-full p-2 border rounded">
      </div>
      
      <div class="mb-4">
        <label class="block mb-2">店铺描述</label>
        <textarea id="editMerchantDesc" class="w-full p-2 border rounded" rows="3"></textarea>
      </div>
      
      <div class="flex justify-end gap-2">
        <button type="button" onclick="closeMerchantEditModal()" class="px-4 py-2 border rounded hover:bg-gray-100">取消</button>
        <button type="submit" class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">保存</button>
      </div>
    </form>
  </div>
</div>

</body>
</html>